﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace RM.Entities.Data
{
    public class BaseManager
    {
        public T GetById<T>(int Id)
        {
            using (ISession session = DataManager.SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(T));
                criteria.Add(Restrictions.Eq("Id", Id));
                criteria.SetMaxResults(1);
                return (T)criteria.UniqueResult();
            }
        }

        public IList<T> GetAll<T>(string OrderBy)
        {
            using (ISession session = DataManager.SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(T));
                return criteria.AddOrder(new Order(OrderBy, true)).List<T>();
            }
        }

        public void Save<T>(T entity)
        {
            using (ISession session = DataManager.SessionFactory.OpenSession())
            {
                session.SaveOrUpdate(entity);
                session.Flush();
                session.Close();
            }
        }

        public void Update<T>(T entity)
        {
            using (ISession session = DataManager.SessionFactory.OpenSession())
            {
                session.Update(entity);
                session.Flush();
            }
        }
    }
}
